package com.eunion.fileserver.upload.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.eunion.fileserver.upload.FileException;
import com.eunion.fileserver.upload.FileUploadAbstract;
import com.eunion.fileserver.upload.FileUploadHelper;
import com.eunion.fileserver.upload.FileVo;
import com.eunion.fileserver.upload.IFileUpload;
import com.eunion.fileserver.upload.ImageCompressUtil;

/**
 * 文件上传本地文件夹的实现.
 * @since 2017年2月17日
 */
public class FileUploadLocal extends FileUploadAbstract implements IFileUpload {

	@Override
	public void uploadFileInputStream(FileVo fv) {
		checkPath(fv);

		String destFilename = FileUploadHelper.getUUID() + fv.getType();
		fv.setNameNew(destFilename);//回写
		InputStream compresInputStream = null;
		try {
			//inpustream 不能2次使用。这里要提取处理转
			byte[] fileByte = ImageCompressUtil.readBytes(fv.getFileInputStream());
			InputStream inputStream = ImageCompressUtil.byte2Input(fileByte);
			fv.setFileInputStream(inputStream);
			LOG.info("文件上传开始 ：{}", fv.getNameOrg());
			String returnRelatedFilePath = fv.getPath();
			String returnFilePath = FileUploadHelper.getInstance().getUploadLocalPath() + fv.getPath();
			File file = new File(returnFilePath);
			if (!file.exists()) {
				boolean mkdir = file.mkdirs();
				LOG.debug("mkdir {} staus {}", file.getAbsolutePath(), mkdir);
			}

			boolean flag = inputstreamToFile(fv.getFileInputStream(), returnFilePath + destFilename);
			returnRelatedFilePath += destFilename;
			LOG.info("文件上传:{} 为:{} ", flag, fv.getPath());
			//再判断是否要写个缩略版本。fullPath
			if (FileUploadHelper.getInstance().getImageCompress()) {
				if (fv.getType().toLowerCase().equals(".jpg") || fv.getType().toLowerCase().equals(".jpeg") || fv.getType().toLowerCase().equals(".png")) {
					String subfix = destFilename.substring(destFilename.lastIndexOf(".") + 1, destFilename.length());
					String newName = ImageCompressUtil.getCompressFileNamePath(destFilename);
					compresInputStream = ImageCompressUtil.compressAutoWidthHeight(fileByte, subfix);

					boolean flagCompress = inputstreamToFile(compresInputStream, returnFilePath + newName);
					LOG.info("文件，现在压缩:{} 为:{} ", flagCompress, newName);
				}
			}
			fv.setUpload(true);
			fv.setRelativePath(returnRelatedFilePath);
		} catch (Exception e) {
			throw new FileException("保存文件出错", e);
		} finally {
			IOUtils.closeQuietly(fv.getFileInputStream());
			IOUtils.closeQuietly(compresInputStream);
		}
	}

	/**
	 * 将输入流写入到文件中.
	 * @param ins 输入流 
	 * @param file 输出文件.
	 * @throws IOException 
	 */
	public boolean inputstreamToFile(InputStream ins, String filePathName)
	    throws IOException {
		OutputStream os = null;
		try {
			os = new FileOutputStream(new File(filePathName));
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			return true;
		} finally {
			IOUtils.closeQuietly(os);
			IOUtils.closeQuietly(ins);
		}
	}

	@Override
	public boolean deleteFile(String deleteFile) {
		String deletePathFile = FileUploadHelper.getInstance().getUploadLocalPath() + deleteFile;
		File file = new File(deletePathFile);
		if (file.exists()) {
			boolean deleteFlag = file.delete();
			LOG.debug("deleteFlag {} staus {}", deletePathFile, deleteFlag);
			return deleteFlag;
		} else {
			return true;
		}
	}

	@Override
	public boolean downloadFile(String source, String destination) {
		source = FileUploadHelper.getInstance().getUploadLocalPath() + source;
		try {
			File f = new File(source);
			if (f.exists() && f.isFile() && f.canRead()) {
				InputStream ins = new FileInputStream(f);
				File fo = new File(destination);
				OutputStream out = null;
				try {
					if (!fo.exists()) {
						fo.createNewFile();
					}
					out = new FileOutputStream(fo);
					if (ins != null && out != null) {
						IOUtils.copy(ins, out);
					}
				} catch (Throwable ex) {
					LOG.error("下载文件出错,{}", ex);
					throw new RuntimeException(ex);
				} finally {
					IOUtils.closeQuietly(ins);
					IOUtils.closeQuietly(out);
				}

			}
		} catch (FileNotFoundException e) {
			LOG.error("待获取的文件未找到：{}", source);
			LOG.error("待获取的文件未找到", e);
		}

		return false;
	}

	@Override
	public InputStream getFileInputStream(String source) {
		source = FileUploadHelper.getInstance().getUploadLocalPath() + source;
		try {
			File f = new File(source);
			if (f.exists() && f.isFile() && f.canRead()) {
				return new FileInputStream(f);
			}
		} catch (FileNotFoundException e) {
			LOG.error("待获取的文件未找到：{}", source);
			LOG.error("待获取的文件未找到", e);
		}
		return null;
	}

	@Override
	public List<String> listFiles(String directory) {
		File f = new File(FileUploadHelper.getInstance().getUploadLocalPath() + directory);
		if (f.exists() && f.isDirectory()) {
			String[] files = f.list();
			if (files != null && files.length > 0) {
				return Arrays.asList(files);
			}
			return null;
		}
		return null;
	}
}
